<?php

/**
 * Member Actions.
 *
 * @package    wildlive
 * @subpackage member
 * @author     Maximilian Lenkeit <dev@lenki.com>
 */
class memberActions extends WildliveActions
{

  //  public function executeIndex (sfWebRequest $request)
  //  {
  //    $this->organizational_unit = $this->getRoute()->getOrganizationalUnit();
  //    $this->members = $this->organizational_unit->retrieveMembers();
  //    $this->members_batch_actions = array('' => 'Bitte wählen...', 'batchDelete' => 'Löschen', 'batchPayMembershipFee' => 'Bezahlen');
  //  }
  

  public function executeRestore (sfWebRequest $request)
  {
    $member = $this->getRoute()
      ->getObject();
    $organizational_unit = $this->getRoute()
      ->getOrganizationalUnit();
    $this->forward404If(! $member->isDeleted());
    
    $member->restore();
    $member->save();
    
    $this->getUser()
      ->setFlash(UserFlash::SUCCESS, sprintf('%s %s wurde erfolgreich wieder hergestellt.', $member->getFirstName(), $member->getLastName()));
    
    $this->redirect($this->generateUrl('organizational_unit_recently_deleted_members', $organizational_unit));
  }

  public function executeRecentlyDeleted (sfWebRequest $request)
  {
    $this->organizational_unit = $this->getRoute()
      ->getObject();
    $this->period = ($this->getUser()
      ->hasCredential('admin') ? 0 : 10);
    $this->members = $this->organizational_unit->retrieveRecentlyDeletedMembers($this->period);
  }

  public function executePayMembershipFee (sfWebRequest $request)
  {
    $year = $request->getParameter('year');
    $member = $this->getRoute()
      ->getObject();
    if (! $member->hasPayedMembershipFee($year))
    {
      $fee = $member->payMembershipFee($year);
      $fee->save();
      $this->getUser()
        ->setFlash(UserFlash::SUCCESS, 
          sprintf('%s %s wurde für das Jahr %s erfolgreich als bezahlt markiert.', $member->getFirstName(), $member->getLastName(), $year));
    }
    $this->redirect($this->generateUrl('organizational_unit_portal', $this->getRoute()
      ->getOrganizationalUnit()));
  }

  public function executeBatchPaymentList (sfWebRequest $request)
  {
    if ($request->hasParameter('year'))
    {
      $this->year = $request->getParameter('year');
    }
    else
    {
      $this->year = date("Y");
    }
    MemberTable::getInstance()->setFiscalYear($this->year);
    $this->organizational_unit = $this->getRoute()
      ->getObject();
    $this->members = $this->organizational_unit->retrieveMembers();
    $this->batch_payment_form = new MembershipFeeBatchPaymentForm($this->members, $this->year);
    $this->year_change_form = new MembershipFeeMassPaymentYearSelectionForm(array(
      'year' => date("Y")));
    $this->year_change_form->setDefault('year', $this->year);
    $this->checked_checkboxes = array();
    foreach ($this->members as $member)
    {
      if ($member->hasPayedMembershipFee($this->year))
      {
        $this->checked_checkboxes[] = $member->getId();
      }
    }
  }

  public function executeBatchPayMembershipFees (sfWebRequest $request)
  {
    $organizational_unit = $this->getRoute()
      ->getObject();
    $year = $request->getParameter('year');
    MemberTable::setFiscalYear($year);
    $members = $organizational_unit->retrieveMembers();
    
    $form = new MembershipFeeBatchPaymentForm($members, $year);
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    
    if ($form->isValid())
    {
      $nb_created = 0;
      $nb_updated = 0;
      $nb_deleted = 0;
      $values = $form->getValues();
      foreach ($members as $member)
      {
        $fee = $member->hasPayedMembershipFee($year);
        if ($fee == false && isset($values[$member->getId()]))
        {
          // Create
          $p = new MembershipFeePayment();
          $p->setYear($year);
          $p->setMemberId($member->getId());
          $p->setDateOfPayment($values[$member->getId()]['date_of_payment']);
          $p->setReference($values[$member->getId()]['reference']);
          $p->setAmount($values[$member->getId()]['amount']);
          $p->save();
          $nb_created ++;
        }
        elseif ($fee != false && isset($values[$member->getId()]))
        {
          // Update
          $p = $member->getMembershipFeePaymentForYear($year);
          $p->setDateOfPayment($values[$member->getId()]['date_of_payment']);
          $p->setReference($values[$member->getId()]['reference']);
          $p->setAmount($values[$member->getId()]['amount']);
          $p->save();
          $nb_updated ++;
        }
        elseif ($fee != false && (! isset($values[$member->getId()]) || empty($values)))
        {
          // Delete
          $p = $member->getMembershipFeePaymentForYear($year);
          $p->delete();
          $nb_deleted ++;
        }
      }
      $this->getContext()
        ->getConfiguration()
        ->loadHelpers('MyText');
      $this->getUser()
        ->setFlash(UserFlash::SUCCESS, 
          sprintf('Für das Jahr wurden %s %s %s erstellt, %s %s aktualisiert und %s %s gelöscht.', $year, $nb_created, 
              _n($nb_created, 'Eintrag', 'Einträge'), $nb_updated, _n($nb_updated, 'Eintrag', 'Einträge'), $nb_deleted, 
              _n($nb_deleted, 'Eintrag', 'Einträge')));
      $this->redirect($this->generateUrl('organizational_unit_portal', $organizational_unit));
    
    }
    else
    {
      $this->batch_payment_form = $form;
      $this->year = $year;
      $this->members = $members;
      $this->year_change_form = new MembershipFeeMassPaymentYearSelectionForm(array(
        'year' => date("Y")));
      $this->year_change_form->setDefault('year', $this->year);
      $this->organizational_unit = $organizational_unit;
      $this->form_errors = BaseForm::collectErrors($form);
      $this->setTemplate('batchPaymentList');
    }
  }

  public function executeShow (sfWebRequest $request)
  {
    $this->member = Doctrine_Core::getTable('Member')->find(array(
      $request->getParameter('id')));
    $this->phone_numbers_landline = array();
    $this->phone_numbers_fax = array();
    $this->phone_numbers_mobile = array();
    foreach ($this->member->getPhoneNumbers() as $phone_number)
    {
      switch ($phone_number->getType())
      {
        case 'landline':
        case '':
          $this->phone_numbers_landline[] = $phone_number;
          break;
        case 'fax':
          $this->phone_numbers_fax[] = $phone_number;
          break;
        case 'mobile':
          $this->phone_numbers_mobile[] = $phone_number;
          break;
      }
    }
    $this->forward404Unless($this->member);
  }

  public function executeNew (sfWebRequest $request, sfForm $form = null)
  {
    $this->organizational_unit = $this->getRoute()
      ->getOrganizationalUnit();
    if (is_null($form))
    {
      $form = new MemberForm(null, array(
        'enabled_organizational_unit_ids' => $this->getUser()
        ->getOwningOrganizationalUnitIds()));
    }
    $this->form = $form;
  }

  public function executeCreate (sfWebRequest $request)
  {
    $this->organizational_unit = $this->getRoute()
      ->getOrganizationalUnit();
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    
    $this->form = new MemberForm(null, array(
      'enabled_organizational_unit_ids' => $this->getUser()
      ->getOwningOrganizationalUnitIds()));
    
    $this->processForm($request, $this->form);
    
    $this->setTemplate('new');
  }

  public function executeEdit (sfWebRequest $request, sfForm $form = null)
  {
    $this->organizational_unit = $this->getRoute()
      ->getOrganizationalUnit();
    $this->forward404Unless($member = Doctrine_Core::getTable('Member')->find(array(
      $request->getParameter('id'))), sprintf('Object member does not exist (%s).', $request->getParameter('id')));
    $this->getLogger()
      ->alert(print_r($member->toArray(true), true));
    if (is_null($form))
    {
      $form = new MemberForm($member, 
          array(
            'enabled_organizational_unit_ids' => $this->getUser()
            ->getOwningOrganizationalUnitIds()));
    }
    $this->form = $form;
  }

  public function executeUpdate (sfWebRequest $request)
  {
    $this->organizational_unit = $this->getRoute()
      ->getOrganizationalUnit();
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($member = Doctrine_Core::getTable('Member')->find(array(
      $request->getParameter('id'))), sprintf('Object member does not exist (%s).', $request->getParameter('id')));
    $this->form = new MemberForm($member, 
        array(
          'enabled_organizational_unit_ids' => $this->getUser()
          ->getOwningOrganizationalUnitIds()));
    
    $this->processForm($request, $this->form);
    
    $this->setTemplate('edit');
  }

  public function executeDelete (sfWebRequest $request)
  {
    //$request->checkCSRFProtection(); // TODO
    

    $this->forward404Unless($member = Doctrine_Core::getTable('Member')->find(array(
      $request->getParameter('id'))), sprintf('Object member does not exist (%s).', $request->getParameter('id')));
    $organizational_unit = $member->getOrganizationalUnit();
    $member->delete();
    
    $this->redirect($this->generateUrl('organizational_unit_portal', $organizational_unit));
  
   #$this->redirect($this->generateUrl('member_index', array('sf_subject' => MemberTable::getInstance()->findAll()->getFirst(), 'unit' => OrganizationalUnitTable::getInstance()->findAll()->getFirst())));
  }

  protected function processAddPhoneNumberForm (sfWebRequest $request, MemberForm $form)
  {
    $this->getLogger()
      ->log('Adding phone number form', sfLogger::INFO);
    $this->getUser()
      ->setFlash('notice', 'add phone number');
    $form->addPreviouslyAddedPhoneNumbers($request->getParameter($form->getName()));
    $form->addPhoneNumber();
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->getObject()
      ->isNew())
    {
      return $this->executeNew($request, $form);
    }
    else
    {
      return $this->executeEdit($request, $form);
    }
  }

  protected function processAddAddressForm (sfWebRequest $request, sfForm $form)
  {
    $this->getUser()
      ->setFlash('notice', 'add address');
    $form->addPreviouslyAddedAddresses($request->getParameter($form->getName()));
    $form->addAddress();
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->getObject()
      ->isNew())
    {
      return $this->executeNew($request, $form);
    }
    else
    {
      return $this->executeEdit($request, $form);
    }
  }

  protected function processForm (sfWebRequest $request, sfForm $form)
  {
    if ($request->getParameter('add_phone_contact_form', false))
    {
      return $this->processAddPhoneNumberForm($request, $form);
    }
    elseif ($request->getParameter('add_address_form', false))
    {
      return $this->processAddAddressForm($request, $form);
    }
    
    try
    {
      $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
      
      if ($form->isValid())
      {
        $is_new = $form->getObject()
          ->isNew();
        $member = $form->save();
        
        if ($is_new)
        {
          $this->getUser()
            ->setFlash(UserFlash::SUCCESS, UserFlash::CREATION_SAVED_SUCCESSFULLY);
        }
        else
        {
          $this->getUser()
            ->setFlash(UserFlash::SUCCESS, UserFlash::CHANGES_SAVED_SUCCESSFULLY);
        }
        
        $this->redirect($this->generateUrl('organizational_unit_portal', $member->getOrganizationalUnit()));
      }
      else
      {
        $this->form_errors = BaseForm::collectErrors($this->form);
      }
    }
    catch (Doctrine_Exception $e)
    {
      $this->getLogger()
        ->emerg($e);
      $this->getUser()
        ->setFlash(UserFlash::ERROR, 'Es kam zu einem unerwarteten Fehler, bitte benachrichtige die Administration.');
      $unit = $this->getRoute()
        ->getOrganizationalUnit();
      $this->redirect($this->generateUrl('organizational_unit_portal', $unit));
    
    }
  }

  public function executeBatch (sfWebRequest $request)
  {
    $this->getUser()
      ->setFlash('notice', 'You must at least select one item.');
    $request->checkCSRFProtection();
    
    if (! $ids = $request->getParameter('ids'))
    {
      $this->getUser()
        ->setFlash('error', 'You must at least select one item.');
    
   #$this->redirect('@members');
    }
    
    if (! $action = $request->getParameter('batch_action'))
    {
      $this->getUser()
        ->setFlash('error', 'You must select an action to execute on the selected items.');
    
   #$this->redirect('@members');
    }
    
    if (! method_exists($this, $method = 'execute' . ucfirst($action)))
    {
      throw new InvalidArgumentException(sprintf('You must create a "%s" method for action "%s"', $method, $action));
    }
    
    //    if (!$this->getUser()->hasCredential($this->configuration->getCredentials($action)))
    //    {
    //      $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
    //    }
    

    $validator = new sfValidatorDoctrineChoice(array(
      'multiple' => true, 'model' => 'Member'));
    try
    {
      // validate ids
      $ids = $validator->clean($ids);
      
      // execute batch
      $this->$method($request);
      $this->getUser()
        ->setFlash('error', 'Batch executed');
    
    }
    catch (sfValidatorError $e)
    {
      $this->getUser()
        ->setFlash('error', 'A problem occurs when deleting the selected items as some items do not exist anymore.');
    }
    
    //$this->redirect('@member_AutoMember');
    $this->redirect('members', $this->getUser()
      ->getOrganisationalEntity());
  }

  protected function executeBatchDelete (sfWebRequest $request)
  {
    $ids = $request->getParameter('ids');
    
    $records = Doctrine_Query::create()->from('Member')
      ->whereIn('id', $ids)
      ->execute();
    
    foreach ($records as $record)
    {
      $record->delete();
    }
    
    $this->getUser()
      ->setFlash('notice', 'The selected items have been deleted successfully.');
    $this->redirect('members', $this->getUser()
      ->getOrganisationalEntity());
  }

  protected function executeBatchPayMembershipFee (sfWebRequest $request)
  {
    $ids = $request->getParameter('ids');
    $year = date("Y");
    
    $records = Doctrine_Query::create()->from('Member')
      ->whereIn('id', $ids)
      ->execute();
    
    foreach ($records as $record)
    {
      $record->payMembershipFee($year);
    }
    
    $this->getUser()
      ->setFlash('notice', 'The selected items have been deleted successfully.');
    $this->redirect('members', $this->getUser()
      ->getOrganisationalEntity());
  
  }
}
